package com.tcwlkj.uuService.update;

import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.Toast;

import com.tcwlkj.uuService.R;
import com.tcwlkj.uuService.utils.ToastUtil;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Url;

/**
 * Created by Administrator on 2017/11/30 0030.
 */

public class DownLoadService extends Service {
    /**
     * 目标文件存储的文件夹路径
     */
    private String  destFileDir = Environment.getExternalStorageDirectory().getPath();
    /**
     * 目标文件存储的文件名
     */
    private String destFileName = "/driver-release.apk";

    private Context mContext;
    private int preProgress = 0;
    private int NOTIFY_ID = 1000;
    private NotificationCompat.Builder builder;
    private NotificationManager notificationManager;
    private Retrofit.Builder retrofit;
//    private String beganUrl;
//    private String endUrl;


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mContext = this;
        String url = intent.getStringExtra("url");
        loadFile(url);
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MsgBinder();
    }

    public class MsgBinder extends Binder {
        /**
         * 获取当前Service的实例
         * @return
         */
        public DownLoadService getService(){
            return DownLoadService.this;
        }
    }
    /**
     * 下载文件
     */
    private void loadFile(String url) {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder();
        }
//        beganUrl = url.substring(0,url.lastIndexOf("/"));
//        endUrl = url.substring(url.lastIndexOf("/")+1);
        // 使用Retrofit进行文件的下载
        retrofit.baseUrl("http://admin.kkptu.com/")
                .client(initOkHttpClient())
                .build()
                .create(IFileLoad.class)
                .loadFile(url)
                .enqueue(new FileCallback(destFileDir, destFileName) {
                    @Override
                    public void onSuccess(File file) {
                        Log.e("zs", "请求成功");
                        // 安装软件
                        onProgressListener.cancleProgress();
                        installApk(file);
                    }
                    @Override
                    public void onLoading(long progress, long total) {
                        if(onProgressListener != null){
                            onProgressListener.onProgress(Integer.parseInt(progress * 100 / total+""));
                        }
                    }
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.e("zs", "请求失败");
                        ToastUtil.getInstance().show("onFailure");
                        onProgressListener.cancleProgress();
                    }
                });
    }

    //http://admin.kkptu.com/Documents/APK/driver-release.apk

    public interface IFileLoad {
        @GET
        Call<ResponseBody> loadFile(@Url String url);
    }
    /**
     * 安装软件
     *
     * @param file
     */
    private void installApk(File file) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //判读版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(this, "com.tcwlkj.uuService.fileprovider", file);//在AndroidManifest中的android:authorities值
            Intent instal = new Intent(Intent.ACTION_VIEW);
            instal.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            instal.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            instal.setDataAndType(apkUri, "application/vnd.android.package-archive");
            startActivity(instal);
        }else{
            //以前的启动方法
            install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            // 执行意图进行安装
            startActivity(install);
        }
    }
    /**
     * 初始化OkHttpClient
     *
     * @return
     */
    private OkHttpClient initOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(100000, TimeUnit.SECONDS);
        builder.networkInterceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse
                        .newBuilder()
                        .body(new FileResponseBody(originalResponse))//将自定义的ResposeBody设置给它
                        .build();
            }
        });
        return builder.build();
    }

    public interface OnProgressListener {
        void onProgress(int progress);
        void cancleProgress();
    }
    /**
     * 更新进度的回调接口
     */
    private OnProgressListener onProgressListener;
    /**
     * 注册回调接口的方法，供外部调用
     * @param onProgressListener
     */
    public void setOnProgressListener(OnProgressListener onProgressListener) {
        this.onProgressListener = onProgressListener;
    }

//    /**
//     * 初始化Notification通知
//     */
//    public void initNotification() {
//        builder = new NotificationCompat.Builder(mContext)
//                .setSmallIcon(R.mipmap.ic_launcher)// 设置通知的图标
//                .setContentText("0%")// 进度Text
//                .setContentTitle("同城跑男更新")// 标题
//                .setProgress(100, 0, false);// 设置进度条
//        notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);// 获取系统通知管理器
//        notificationManager.notify(NOTIFY_ID, builder.build());// 发送通知
//    }
//
//    /**
//     * 更新通知
//     */
//    public void updateNotification(long progress) {
//        int currProgress = (int) progress;
//        if (preProgress < currProgress) {
//            builder.setContentText(progress + "%");
//            builder.setProgress(100, (int) progress, false);
//            notificationManager.notify(NOTIFY_ID, builder.build());
//        }
//        preProgress = (int) progress;
//    }
//
//    /**
//     * 取消通知
//     */
//    public void cancelNotification() {
//        notificationManager.cancel(NOTIFY_ID);
//    }

}
